import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

@WebServlet("/delete_book")
public class DeleteBook extends HttpServlet {

    private static final String DB_URL = "jdbc:mysql://127.0.0.1:3306/linux_exam?useSSL=false&serverTimezone=UTC";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "1qaz@WSX#EDC";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*"); // 允许所有来源跨域
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); // 允许的方法
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization"); // 允许的请求头
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter out = resp.getWriter();

        // 获取请求参数
        String number = req.getParameter("number");

        // 参数验证
        if (number == null) {
            out.println("{\"error\": \"缺少必要参数\"}");
            return;
        }

        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD)) {
            // 准备SQL语句
            String sql = "DELETE FROM t_book WHERE number = ?";
            try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
                pstmt.setString(1, number);

                // 执行删除
                int rows = pstmt.executeUpdate();
                if (rows > 0) {
                    JSONObject result = new JSONObject();
                    result.put("message", "success");
                    out.println(result.toString());
                } else {
                    out.println("{\"error\": \"删除失败\"}");
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            out.println("{\"error\": \"数据库错误: " + e.getMessage() + "\"}");
        } catch (Exception e) {
            e.printStackTrace();
            out.println("{\"error\": \"服务器内部错误\"}");
        }
    }
}
